<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/3
 * Time: 14:49
 */

namespace app\admin\controller;

use app\admin\model\Users;
use app\admin\model\Users as Users_model;
use app\api\controller\Client;
use app\queue\jobs\Wechat;
use app\common\logic\Login as login_logic;
use think\Cache;
use think\Controller;
use think\Session;
use think\Db;

/**
 * Class Login
 * 主要处理登录逻辑
 * @package app\admin\controller
 * @internal
 */
class Login extends Controller
{

    /**
     *跳转到登录页面
     * @icon wocap
     */
    public function index()
    {
        $this->redirect('login');
    }

    /**
     * 登陆显示
     * @return mixed
     */
    public function login()
    {
//        $Client = new Client();
//        $alluserinfo = collect($Client->getAllUserInfo(true))->all();
////        $alluserinfo->where('phone', 1)->collapse()->all();
//        halt($alluserinfo);
//        if (isIeBrowser()) return $this->fetch('ie');
        if(isIeBrowser()){
            $this->redirect(url('admin/login/ie'));
        }
        if (is_login()) $this->redirect('admin/business/index');
        return $this->fetch('login');
    }


    /**
     * 登陆显示
     * @return mixed
     */
    public function loginadmintest()
    {
        if (isIeBrowser()) return $this->fetch('ie');
        if (is_login()) $this->redirect('admin/index/index');
        return $this->fetch('admintest');
    }

    /**
     *密码登陆验证
     */
    public function checklogin()
    {
        if (!request()->isAjax()) $this->error("提交方式错误！", url('admin/Login/login'));
        $username = request()->param('username');
        $password = request()->param('password');
        $login_logic = new \app\common\logic\Login();
        $re = $login_logic->executLogin($username,$password);
        if ($re['result'] == 1) {
             $this->success('恭喜您，登陆成功', url('admin/yewu/olist'));
        } else {
             $this->error($re['msg'], url('admin/Login/login'));
        }
    }

    /**
     *验证码登陆验证
     */
    public function checkCodelogin()
    {
        if (!request()->isAjax()) $this->error("提交方式错误！", url('admin/Login/login'));
        $admin_username = request()->param('username');
        $recode = request()->param('code');
        $data = $this->getUserinfo($admin_username);
        if (empty($data)) $this->error('用户名错误！');
        $code = Session::get('user_' . $data['id']);
        if ($code === (int)$recode) {
            login_logic::auto_login($data);
            Session::delete('user_' . $data['id']);
            $this->success('恭喜您，登陆成功', url('admin/yewu/olist'));
        } else {
            $this->error('验证码错误！请重新输入', url('admin/Login/login'));
        }
    }

    /**
     *清理缓存
     */
    public function clear()
    {
        Cache::clear();
        if (config('admin.log')['clear_on']) {
            // 删除指定时间的日志(默认1个月)
            $path = list_file(RUNTIME_PATH);
            foreach ($path as $f) {
                if ($f ['isDir']) {
                    foreach (list_file($f ['pathname']) as $ff) {
                        if ($ff ['isDir']) {
                            foreach (list_file($ff['pathname']) as $fff) {
                                if ($fff ['isFile']) {
                                    @unlink($fff['pathname']);
                                }
                            }
                        } else {
                            @unlink($ff ['pathname']);
                        }
                    }
                }
            }
        }
        $this->success('清理缓存成功');
    }


    /**
     * 退出登录
     */
    public function logout()
    {
        $arr = session('admin_user');
        logdaily(2,$arr['username'],'退出登陆');
        session('admin_user', null);
        $this->redirect('admin/Login/login');
    }

    /**
     * 修改密码
     * @return mixed
     */
    public function editpassword()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            //获取参数
            empty($data['old']) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($data['repassword']) && $this->error('请输入确认密码');
            if ($data['password'] !== $data['repassword']) {
                $this->error('您输入的新密码与确认密码不一致');
            }
            $users = Users::get(['id' => $data['id'], 'password' => md5($data['old'])]);
            if ($users) {
                $a = Users::update(['id' => $data['id'], 'password' => md5($data['password'])]);
                if ($a) {
                    session('admin_user', null);
                    $this->success('修改成功，请重新登陆！', url('login'));
                } else {
                    $this->error('修改失败！请联系管理员！');
                }
            } else {
                $this->error('原始密码不正确！');
            }
        } else {
            $id = session('admin_user.adminid');
            $this->assign("id", $id);
            return $this->fetch();
        }
    }

    /**
     *发送微信验证码
     */
    public function sendWechat()
    {
        $username = $this->request->param('username');
        $data = $this->getUserinfo($username);
        if (empty($data)) {
            $this->error('用户名不存在');
        } else {
            if ($data['status'] == 0) {
                $this->error('该账号已被禁用！请联系管理员！');
                exit;
            }
            if ($data['weixinstatus'] != 1) {
                $this->error('请绑定微信公众号之后在登陆系统！');
                exit;
            }
        }
        $code = rand(1000, 9999);
        $datas = [
            'receive_id' => $data['id'],
            'send_id' => 1,
            'order_id' => $data['phone'],
            'temp_id' => 'yhsxBWFn39eZWM1gBSD-RJhzduP0C4wZ_SK3yYDtIFQ',
            'url' => '',
            'data' => [
                'first' => ['value' => $username . ' 您的登陆验证码信息如下:', 'color' => '#173177'],
                'keyword1' => ['value' => "GOS电商管理系统登陆验证码", 'color' => '#173177'],
                'keyword2' => ['value' => $code, 'color' => '#FF0000'],
                'keyword3' => ['value' => time_format(time() + 300, "Y-m-d H:i"), 'color' => '#173177'],
                'remark' => ['value' => "感谢使用GOS电商管理系统.", 'color' => '#173177'],
            ]
        ];
        $datainfo = \app\admin\logic\Wechat::HandleData($datas);
        $reult =Wechat::doJob($datainfo);
        if ($reult['errmsg'] == 'ok') {
            Session::set('user_' . $data['id'], $code);
            $this->success('微信验证码发送成功!请注意查收');
        } else {
            $this->error('微信验证码发送失败！请联系管理员');
        }
    }

    /**
     * 获取用户的信息
     * @param $username
     * @return array
     * @author: Huang
     */
    protected function getUserinfo($username)
    {
        $alluserinfo = collect(db('users')->select());
        if (is_numeric($username)) {
            $data = $alluserinfo->where('phone', $username)->collapse()->all();;
        } else {
            $data = $alluserinfo->where('username', $username)->collapse()->all();;
        }
        return $data;
    }

    /**
     * ie浏览器
     * @return mixed
     * @author: Huang
     */
    public function Ie()
    {
        if(!isIeBrowser()){
            $this->redirect(url('admin/login/login'));
        }
        return $this->fetch('loginie');
    }
}